<?php
namespace App\Admin\Utils;

use App\Wen\Utils\FileUtils;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use ZipArchive;

class DownUtils{

    /** 下载附件，然后打包
     * @param $arr [ [name=>url], ]
     */
    public static function down_invite_temp_code($arr){
        $zipFileName = 'itc_'.current_time().'.zip';
        $zipFilePath = public_path('storage/tmp/' . $zipFileName);

        $zip = new ZipArchive;
        $zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
        foreach ($arr as $item){
            $zip->addFromString($item['name'].'.'.FileUtils::get_file_extension_from_url($item['url']), file_get_contents($item['url']));
        }
        $zip->close();
        return env('APP_URL').'/storage/tmp/'.$zipFileName;
    }


    /** 下载附件，然后打包
     * @param $arr [ [name=>url], ]
     */
    public static function down_invite_temp_code_with_bg($arr, $the_bg)
    {
        $zipFileName = 'itc_bg_' . time() . '.zip';
        $zipFilePath = public_path('storage/tmp/' . $zipFileName);

        // 确保保存 ZIP 文件的目录存在
        $zipDir = dirname($zipFilePath);
        if (!is_dir($zipDir)) {
            mkdir($zipDir, 0777, true);
        }

        $zip = new ZipArchive;
        if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            throw new \Exception("Cannot open ZIP file at: $zipFilePath");
        }

        try {
            foreach ($arr as $item) {
                $imageUrl = $the_bg['img'];
                $qrCodeUrl = $item['url'];
                $xPercent = round(($the_bg['x_rate'] ?? 0) / 100, 2); // 默认值为0
                $yPercent = round(($the_bg['y_rate'] ?? 0) / 100, 2); // 默认值为0
                $scale = $the_bg['c_rate'] ?? 1; // 默认值为1

                // 加载主图像
                $image = Image::make($imageUrl);

                // 加载二维码图像
                $qrCode = Image::make($qrCodeUrl);

                // 调整二维码图像大小
                $qrCode->resize($qrCode->width() * $scale, $qrCode->height() * $scale);

                // 计算二维码图像在主图像中的位置
                $x = $image->width() * $xPercent - ($qrCode->width() / 2);
                $y = $image->height() * $yPercent - ($qrCode->height() / 2);

                // 将二维码图像粘贴到主图像上
                $image->insert($qrCode, 'top-left', intval($x), intval($y));

                // 将生成的图像数据直接添加到 ZIP 文件中
                $imageData = $image->encode('jpg');
                $zip->addFromString($item['name'] . '.jpg', $imageData);

                // 释放图像资源
                $image->destroy();
                $qrCode->destroy();
            }
        } catch (\Exception $e) {
            // 在发生异常时关闭 ZIP 并删除已创建的文件
            $zip->close();
            @unlink($zipFilePath);
            throw $e;
        }

        try {
            if ($zip->close() === false) {
                throw new \Exception("Failed to close ZIP file: $zipFilePath");
            }
        } catch (\Exception $e) {
            throw $e;
        }

        if (!file_exists($zipFilePath)) {
            throw new \Exception("ZIP file was not created: $zipFilePath");
        }

        return env('APP_URL') . '/storage/tmp/' . $zipFileName;
    }
}
